package com.example.springapplicationdemo.vo;


import com.example.springapplicationdemo.exception.BusinessException;
import com.google.common.collect.Maps;
import lombok.Data;

import java.util.Map;

/**
 * 对返回结果的统一封装
 * @param <T>
 */
@Data
public class RestResVo<T> {
    public static final int ERROR = -1;
    public static final int FAIL = 0;
    public static final int SUCCESS = 1;
    private int status;
    private String message;
    private String timestamp = String.valueOf(System.currentTimeMillis());
    private T data;

    /**
     * 成功
     * @param t
     * @param <T>
     * @return
     */
    public static  <T> RestResVo<T> success(T t){
        RestResVo<T> response = new RestResVo<>();
        response.setStatus(SUCCESS);
        response.setMessage("SUCCESS");
        response.setData(t);
        return response;
    }

    /**
     * 异常
     * @param e
     * @param <T>
     * @return
     */
    public static  <T> RestResVo<T> error(BusinessException e){
        RestResVo<T> response = new RestResVo<>();
        response.setStatus(e.getCode());
        response.setMessage(e.getMsg());
        response.setData(null);
        return response;
    }


    /**
     * 异常
     * @param e
     * @param <T>
     * @return
     */
    public static <T> RestResVo<T> error(Throwable e){
        RestResVo<T> response = new RestResVo<>();
        response.setStatus(ERROR);
        response.setMessage(e.toString());
        response.setData(null);
        return response;
    }

    /**
     * 失败
     * @param msg
     * @param <T>
     * @return
     */
    public static  <T> RestResVo<T> fail(String msg){
        RestResVo<T> response = new RestResVo<>();
        response.setStatus(FAIL);
        response.setMessage(msg);
        return response;
    }

    public Map<String, Object> toMapData(){
        Map<String, Object> data = Maps.newHashMap();
        data.put("status", getStatus());
        data.put("message", getMessage());
        data.put("timestamp", getTimestamp());
        data.put("data", getData());
        return data;
    }


}
